package com.naiterui.ehp.bs.doctor.controller;

import cn.hutool.core.map.MapUtil;
import com.naiterui.ehp.bp.bo.medication.MedicationDefaultUsageBO;
import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bs.doctor.exception.ExceptionCodes;
import com.naiterui.ehp.bs.doctor.remote.AdRemoter;
import com.naiterui.ehp.bs.doctor.utils.B2cGoodsAPIUtil;
import com.naiterui.ehp.bs.doctor.vo.medication.MedicatioInventorySaleVO;
import com.naiterui.ehp.bs.doctor.vo.medication.MedicationDefaultUsageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = {SwaggerTag.DOCTOR + SwaggerTag.MEDICINE_DRUG})
@RequestMapping("ad/medication")
@RestController
public class AdMedicationController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdMedicationController.class);

    @Autowired
    private AdRemoter remoter;

    /**
     * 获取商品库存信息
     * MedicationController.getInventoryInfo()
     *
     * @param doctorId
     * @param skuIds
     *
     * @return
     *
     * @Author YongYang
     * @Date 2016年10月10日
     * @since 1.0.0
     */
    @ApiOperation(value = "获取商品库存信息接口", notes = "用法用量-根据商品skuids查询商品预售、库存、限购细信息", httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "doctorId", value = "医生ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "skuIds", value = "药品skuId集合", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "nums", value = "药品数量", required = true, dataType = "long", paramType = "query"), @ApiImplicitParam(name =
            "patientId", value = "患者ID", required = true, dataType = "long", paramType = "query")})
    @RequestMapping("/getInventoryInfo")
    public ResponseVO<List<MedicatioInventorySaleVO>> getInventoryInfo(Long doctorId, String skuIds, String nums, Long patientId)
            throws Exception {

        LOGGER.info("medication getInventoryInfo param: doctorId{},skuIds{},nums{},patientId{}", doctorId, skuIds, nums, patientId);

        List<MedicatioInventorySaleVO> result;
        if (doctorId == null || StringUtils.isEmpty(skuIds) || StringUtils.isEmpty(nums)) {
            LOGGER.error("doctorId：{},skuIds:{},nums:{},patientId:{}", doctorId, skuIds, nums, patientId);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        String[] skuIdArr = skuIds.split(",");
        String[] numArr = nums.split(",");
        List<Map<String, Object>> params = new ArrayList<>();
        int i = 0;
        for (String skuId : skuIdArr) {
            Map<String, Object> map = new HashMap<>();
            map.put("skuId", skuId);
            map.put("num", numArr[i]);
            params.add(map);
            i++;
        }
        // 调用b2c
        Map<Long, MedicatioInventorySaleVO> data = B2cGoodsAPIUtil.getInventoryInfoList(params);
        result = Arrays.stream(skuIdArr).map(skuId -> data.get(Long.parseLong(skuId))).collect(Collectors.toList());

        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, result);
    }

    /**
     * 获取药品的默认用法用量
     * MedicationController.getMedicationDefaultUsage()
     *
     * @param skuIds
     *
     * @return
     *
     * @Author lichaopi
     * @Date 2017年12月15日
     * @since 1.0.0
     */
    @ApiOperation(value = "药品的默认用法用量", notes = "推荐时药品的默认用法用量", httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "skuIds", value = "药品skuId字符串(1,2)", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "String", paramType = "query")})
    @RequestMapping("getDefaultUsage")
    public ResponseVO<List<MedicationDefaultUsageVO>> getDefaultUsage(String skuIds) throws Exception {
        LOGGER.info("获取药品的默认用法用量,skuIds:{}", skuIds);
        if (StringUtils.isEmpty(skuIds)) {
            LOGGER.error("获取药品的默认用法用量参数错误,skuIds:{}", skuIds);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }

        Map<Long, MedicationDefaultUsageBO> boMap = this.remoter.getDefaultUsage(skuIds);
        List<MedicationDefaultUsageVO> voList = new ArrayList<>();

        if (MapUtil.isNotEmpty(boMap)) {
            for (MedicationDefaultUsageBO bo : boMap.values()) {
                MedicationDefaultUsageVO vo = new MedicationDefaultUsageVO();
                vo.setSkuId(bo.getSkuId());
                vo.setDosageCount(bo.getDosageCount());
                vo.setDosageCycle(bo.getDosageCycle());
                vo.setDosageCycleUnit(bo.getDosageCycleUnit());
                vo.setDosageStr(bo.getDosageStr());
                vo.setEachDosageCount(bo.getEachDosageCount());
                vo.setEachDoseUnit(bo.getEachDoseUnit());
                vo.setPackagSpec(bo.getPackagSpec());
                vo.setQuantityUnit(bo.getQuantityUnit());
                vo.setUsageMethod(bo.getUsageMethod() == null ? "" : bo.getUsageMethod());
                vo.setUsageTime(bo.getUsageTime() == null ? "" : bo.getUsageTime());
                vo.setFrequencyMax(bo.getFrequencyMax());
                vo.setFrequencyMin(bo.getFrequencyMin());
                vo.setDoseMax(bo.getDoseMax());
                vo.setDoseMin(bo.getDoseMin());
                vo.setMedicationCycleMax(bo.getMedicationCycleMax());
                vo.setMedicineMinUnit(bo.getMedicineMinUnit());
                voList.add(vo);
            }
        }
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, voList);
    }

}
